package com.zjy.pet.service.impl;

import com.zjy.basic.commonenum.ErrorCode;
import com.zjy.basic.domain.Point;
import com.zjy.basic.domain.dto.AcceptOrderDto;
import com.zjy.basic.exception.CustomException;
import com.zjy.basic.util.*;
import com.zjy.org.domain.Shop;
import com.zjy.org.mapper.ShopMapper;
import com.zjy.pet.domain.OrderPetAcquisition;
import com.zjy.pet.domain.Pet;
import com.zjy.pet.domain.SearchMasterMsg;
import com.zjy.pet.domain.SearchMasterMsgAuditLog;
import com.zjy.pet.mapper.OrderPetAcquisitionMapper;
import com.zjy.pet.mapper.PetMapper;
import com.zjy.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.zjy.pet.mapper.SearchMasterMsgMapper;
import com.zjy.pet.service.SearchMasterMsgService;
import com.zjy.basic.service.impl.BaseServiceImpl;
import com.zjy.user.domain.Logininfo;
import com.zjy.user.domain.User;
import com.zjy.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements SearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    /**
     * 发布寻主消息
     * @param searchMasterMsg
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) throws Exception {
        //获取当前登录用户的信息
        Logininfo logininfo = CurrentLoginInfoUtil.currentLoginInfo(request);
        //判断登录信息是否存在
        if (logininfo == null){
            throw new CustomException(ErrorCode.LOGININFO_NOT_FOUND.getCode());
        }
        //通过logininfoid获取user信息
        User user = userMapper.findByLoginInfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        //先把msg入库，设置msg信息为待审核，这里我是在实体类设置了默认值的，所以不用再设置了
//        searchMasterMsg.setState(0);
        searchMasterMsgMapper.add(searchMasterMsg);
        //审核前端用户填写的信息是否违规(百度AI智能审核)
        Boolean b1 = BaiduAuditUtils.TextCensor(searchMasterMsg.getTitle());
        Boolean b2 = BaiduAuditUtils.TextCensor(searchMasterMsg.getName());
        Boolean b3 = BaiduAuditUtils.TextCensor(searchMasterMsg.getCoatColor());
        if (b1 && b2 && b3){
            //审核通过，修改状态审核通过，查询50km内的店铺，分配给寻主消息
            //先修改状态为通过
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功");
            //保存审核日志信息
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());//设置寻主消息id
            log.setState(1);//设置审核状态
//            log.setAuditTime(new Date()); //在实体类设置了，不用再new一个时间
            searchMasterMsgAuditLogMapper.add(log);
            //使用工具类获取寻主消息地址的经纬度
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            //查询出所有的店铺
            List<Shop> shops = shopMapper.findAllAvailableShops();
            //使用工具类计算50km内最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shops);
            if (nearestShop!=null){
                searchMasterMsg.setShopId(nearestShop.getId());
            }
        }else {
            //审核不通过，修改状态驳回，发送短信或邮件提醒用户。
            searchMasterMsg.setState(-1);
            searchMasterMsg.setNote("审核失败");
//            SmsUtil.sendSms(user.getPhone(),"提交的寻主信息不合法，请修改后重新提交");
            //保存审核日志信息
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);
            return AjaxResult.me().setSuccess(false).setMsg("审核未通过，请从新填写信息");
        }
        //更新一下寻主消息
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me();
    }

    /**
     * 拒单
     * @param id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult reject(Long id) {
        //查询订单是否在进行中
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.findByMsgId(id);
        if(orders.size() > 0){
            for (OrderPetAcquisition order : orders) {
                if(order.getState() == 0){
                    throw new CustomException("此订单正在进行中,请勿重复接单");
                }
            }
        }

        //通过寻主消息id查询寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(id);
        //把寻主消息的shopid置空
        searchMasterMsg.setShopId(null);
        //更新寻主消息
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me();
    }

    /**
     * 接单
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult accept(AcceptOrderDto dto) {
        //查询订单是否在进行中
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.findByMsgId(dto.getMsgId());
        if(orders.size() > 0){
            for (OrderPetAcquisition order : orders) {
                if(order.getState() == 0){
                    throw new CustomException("此订单正在进行中,请勿重复接单");
                }
            }
        }
        SearchMasterMsg msg = searchMasterMsgMapper.findById(dto.getMsgId());
        //生成狗子
        Pet pet = msg2pet(dto, msg);
        petMapper.add(pet);
        //生成收购订单
        OrderPetAcquisition opa = msg2order(dto, msg, pet);
        orderPetAcquisitionMapper.add(opa);
        return AjaxResult.me();
    }

    private OrderPetAcquisition msg2order(AcceptOrderDto dto, SearchMasterMsg msg, Pet pet) {
        OrderPetAcquisition opa = new OrderPetAcquisition();
        opa.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getMsgId()));
        opa.setDigest(dto.getNote());
        opa.setLastcomfirmtime(new Date(System.currentTimeMillis()+3*24*60*60*1000));
        opa.setState(0);
        opa.setPrice(msg.getPrice());
        opa.setPetId(pet.getId());
        opa.setUserId(msg.getUserId());
        opa.setShopId(msg.getShopId());
        opa.setAddress(msg.getAddress());
        opa.setEmpId(dto.getHandler());
        opa.setSearchMasterMsgId(msg.getId());
        return opa;
    }

    /**
     * 通过寻主消息初始化狗子信息
     * @param dto
     */
    private Pet msg2pet(AcceptOrderDto dto, SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setState(0);
        pet.setTypeId(msg.getPetType());
        pet.setCreatetime(new Date());
        pet.setShopId(msg.getShopId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
